
#coding=utf-8

import unittest
import importlib
import json

from global_utils.log import logger

from global_utils.http_protocol import HttpHelp
from global_utils.register_assert import AssertRegister
from global_utils.mysql_helper import DBConn
from global_utils.runmodeconfig import RunModeConfig
from global_utils.parser_ws_config import WSCONFIG

print WSCONFIG.get_db_info

conn=DBConn(WSCONFIG.get_db_info) 

class InterfaceTestCase(unittest.TestCase):
    
    def __init__(self,case_info,methodName='runTest'):
        super(InterfaceTestCase,self).__init__(methodName)
        self.caseId=case_info["data"]["caseId"]
        self.caseName=case_info["data"]["caseName"]
        self.caseDesc=case_info["data"]["caseDesc"]
        self.project=case_info["data"]["project"]
        self.interface=case_info["data"]["interface"]
        self.method=case_info["data"]["method"]    
        self.url=case_info["data"]["url"]
        self.requestBody=case_info["data"]["requestBody"]
        self.headers=case_info["data"]["headers"]
        self.assertMethod=case_info["data"]["assertMethod"]

        
    def setUp(self):
        dict_assertMethod = json.loads(self.assertMethod)
        assert_method=dict_assertMethod["method"].encode("utf-8")
        self.assert_args=dict_assertMethod["args"]
        moudel_class=importlib.import_module(("".join(("process_assert.",assert_method))))
        self.assert_method=AssertRegister.register(moudel_class,assert_method,"process")
        
    def tearDown(self):
        case_state=self.assert_result["case_state"]
        fail_cause=self.assert_result["fail_cause"]
        print type(fail_cause)
        
        SQL='''
            insert into `result_detail` ( `case_project`, `case_interface`, `case_name`, `case_desc`, `case_method`, `case_url`, `case_request`,`case_state`,`fail_cause`) 
            values('%s','%s','%s','%s','%s','%s','%s',%d,%s)
        ''' % (self.project.encode("utf-8"),self.interface.encode("utf-8"),self.caseName.encode("utf-8"),self.caseDesc.encode("utf-8"),self.method.encode("utf-8"),self.url.encode("utf-8"),self.requestBody.encode("utf-8"),case_state,fail_cause)
        print SQL
        conn.execute(SQL)
        
    def runTest(self):
        
        response=HttpHelp.post(self.url, json.loads(self.headers), self.requestBody)
        
        #断言
        try:
            self.assert_result=self.assert_method("request",response,self.assert_args).process()
        except Exception as e:
            logger.error(e)
    


if __name__=="__main__":
    from get_case.get_test_case import TestCase
    caseinfo=TestCase(1).get_case
    case=InterfaceTestCase(caseinfo)
    suite = unittest.TestSuite()
    suite.addTests([case,])
    runner=unittest.TextTestRunner()
    runner.run(suite)



